import moment from 'moment';
import JSEncrypt from 'jsencrypt';
import CryptoJS from 'crypto-js';

export function formatDate(timeStr, cformat = 'YYYY-MM-DD') {
  return timeStr ? moment(timeStr, cformat) : null;
}

export function formatMsgTime(dateTime) {
  // var dateTime = new Date(timespan);
  const year = dateTime.getFullYear();
  const month = dateTime.getMonth() + 1;
  const day = dateTime.getDate();
  const hour = dateTime.getHours();
  const minute = dateTime.getMinutes();
  const now = new Date();
  const nowNew = Date.parse(now.toDateString()); // typescript转换写法

  let milliseconds = 0;
  let timeSpanStr;

  milliseconds = nowNew - dateTime.valueOf();

  if (milliseconds <= 1000 * 60 * 1) {
    timeSpanStr = '刚刚';
  } else if (1000 * 60 * 1 < milliseconds && milliseconds <= 1000 * 60 * 60) {
    timeSpanStr = `${Math.round(milliseconds / (1000 * 60))}分钟前`;
  } else if (1000 * 60 * 60 * 1 < milliseconds && milliseconds <= 1000 * 60 * 60 * 24) {
    timeSpanStr = `${Math.round(milliseconds / (1000 * 60 * 60))}小时前`;
  } else if (1000 * 60 * 60 * 24 < milliseconds && milliseconds <= 1000 * 60 * 60 * 24 * 15) {
    timeSpanStr = `${Math.round(milliseconds / (1000 * 60 * 60 * 24))}天前`;
  } else if (milliseconds > 1000 * 60 * 60 * 24 * 15 && year === now.getFullYear()) {
    timeSpanStr = `${month}-${day} ${hour}:${minute}`;
  } else {
    timeSpanStr = `${year}-${month}-${day} ${hour}:${minute}`;
  }
  return timeSpanStr;
}
const PUB_KEY = `
-----BEGIN PUBLIC KEY-----
MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBAPLo4Rz+9sL1z08xv+jvevccUIN8lAFF6mroUz2XQAxLaQ4YQ0T0TFNQhWNDo5pcU9Iwyp1P3T45ocZ8/Ia93tcCAwEAAQ==
-----END PUBLIC KEY-----`;
// 公钥加密
export function encrypt(text) {
  const encryptObj = new JSEncrypt();
  encryptObj.setPublicKey(PUB_KEY);
  const encrypted = encryptObj.encrypt(text);
  return encrypted;
}

export const decrypt = word => {
  const key = CryptoJS.enc.Utf8.parse('liantong20190410');
  const options = {
    mode: CryptoJS.mode.ECB,
    padding: CryptoJS.pad.Pkcs7,
  };
  const decryptedData = CryptoJS.AES.decrypt(word, key, options);
  const decryptedStr = decryptedData.toString(CryptoJS.enc.Utf8);
  return decryptedStr;
};
